package com.bxd.baodan.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.activity.FamilyManagerActivity;
import com.bxd.baodan.activity.LoginActivity;
import com.bxd.baodan.activity.MainActivity;
import com.bxd.baodan.activity.MsgActivity;
import com.bxd.baodan.activity.MyFavorateActivity;
import com.bxd.baodan.activity.MyQuestionActivity;
import com.bxd.baodan.activity.ReportActivity;
import com.bxd.baodan.activity.SettingActivity;
import com.bxd.baodan.activity.ShellActivity;
import com.bxd.baodan.activity.UserSettingActivity;
import com.bxd.baodan.activity.WebViewPager;
import com.bxd.baodan.adapter.CommonAdapter;
import com.bxd.baodan.adapter.ViewHolder;
import com.bxd.baodan.app.Constant;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.app.SharedPreferanceKey;
import com.bxd.baodan.item.SettingItem;
import com.bxd.baodan.item.SettingItem.SettingBean;
import com.bxd.baodan.util.GlideUtil;
import com.bxd.baodan.util.ImageUtil;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.SpUtil;
import com.bxd.baodan.util.Utils;
import com.bxd.baodan.widget.MyListView;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

public class MainSettingFragment extends BaseFragment implements OnClickListener {


    private Context context;
    private View view;
    private TextView login;
    private TextView dec;


    public ImageView my_msg;
    private LinearLayout msg_ly;
    private RelativeLayout loginLayout;

    private ImageView avatar;
    private TextView report;
    private TextView myCollect;
    private TextView my_answer;
    private LinearLayout gift;
    private LinearLayout invite;
    private LinearLayout feedback;
    private LinearLayout setting;
    private LinearLayout dingdan, my_fam;
    private MyListView mLv;
    private CommonAdapter<SettingBean> apandAdapter;
    private List<SettingBean> settingData = new ArrayList<>();


    private BroadcastReceiver receiveBroadCast;
    private TextView shell;
    private LinearLayout shell_ly;

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = View.inflate(this.getActivity(), R.layout.fragment_setting, null);
        }
        ViewGroup viewGroup = (ViewGroup) view.getParent();

        if (viewGroup != null) {
            viewGroup.removeAllViewsInLayout();
        }

        context = getActivity();

        return view;

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


        initBroadCastReceiver();

        view.setPadding(view.getPaddingLeft(), view.getPaddingTop() + getStatusBarHeight(),
                view.getPaddingRight(), view.getPaddingBottom());
        avatar = (ImageView) view.findViewById(R.id.avator);

        avatar.setFocusable(true);
        avatar.setFocusableInTouchMode(true);
        avatar.requestFocus();
        login = (TextView) view.findViewById(R.id.denglu);
        dec = (TextView) view.findViewById(R.id.dec);

        my_msg = (ImageView) view.findViewById(R.id.msg);

        if (((MainActivity) getActivity()).hasUnRead) {
            my_msg.setVisibility(View.VISIBLE);

        } else {
            my_msg.setVisibility(View.GONE);
        }
        msg_ly = (LinearLayout) view.findViewById(R.id.msg_ly);
        loginLayout = (RelativeLayout) view.findViewById(R.id.login_layout);
        avatar = (ImageView) view.findViewById(R.id.avator);
        report = (TextView) view.findViewById(R.id.report);
        myCollect = (TextView) view.findViewById(R.id.my_collect);
        my_answer = (TextView) view.findViewById(R.id.my_answer);
        mLv = (MyListView) view.findViewById(R.id.setting_lv);

        gift = (LinearLayout) view.findViewById(R.id.licai);
        invite = (LinearLayout) view.findViewById(R.id.invite);
        feedback = (LinearLayout) view.findViewById(R.id.feedback);
        setting = (LinearLayout) view.findViewById(R.id.setting);
        dingdan = (LinearLayout) view.findViewById(R.id.dingdan);
        my_fam = (LinearLayout) view.findViewById(R.id.my_fam);
        shell_ly = (LinearLayout) view.findViewById(R.id.shell_ly);
        shell = (TextView) view.findViewById(R.id.shell);

        setAdapter();
        mLv.setAdapter(apandAdapter);

        getExpandData();


        loginLayout.setOnClickListener(this);
        msg_ly.setOnClickListener(this);
        report.setOnClickListener(this);
        myCollect.setOnClickListener(this);
        my_answer.setOnClickListener(this);

        my_fam.setOnClickListener(this);
        gift.setOnClickListener(this);
        invite.setOnClickListener(this);
        feedback.setOnClickListener(this);
        setting.setOnClickListener(this);
        dingdan.setOnClickListener(this);
        shell_ly.setOnClickListener(this);


        loadLoginInfo();
        updateShell();



    }

    private void getExpandData() {
        NetUtil netUtil = new NetUtil(getActivity(), JsonApi.USER_SUDOKULIST);
        netUtil.postRequest("", new NetUtil.RequestStringListener() {
            @Override
            public void onComplete(String result) {
                SettingItem settingItem = new Gson().fromJson(result, SettingItem.class);
                settingData.clear();
                settingData.addAll(settingItem.data.list);
                apandAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(String result) {
            }
        });
    }

    public void setAdapter() {
        apandAdapter = new CommonAdapter<SettingBean>(getActivity(), settingData, R.layout.setting_item) {
            @Override
            public void convert(final ViewHolder holder, final SettingBean item) {
                holder.setText(R.id.title, item.title);
                GlideUtil.loadImage(getActivity(), item.ico, (ImageView) holder.getView(R.id.icon));
                holder.getView(R.id.isHot).setVisibility(item.hot.equals("1") ? View.VISIBLE : View.GONE);
                holder.getView(R.id.main).setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        MobclickAgent.onEvent(App.getContext(), "v6_1_3_WD_expand");
                        String url = item.path.gotoUrl;
                        String clickKey = "v6_1_2_WD_expand_" + (holder.getPosition() + 1);

                        if (item.isLogin.equals("1")) {
                            if (loginStatus()) {
                                if (url.contains("{uid}")) {
                                    url.replace("{uid}", LoginInfo.getInstance().getUid());
                                    MobclickAgent.onEvent(App.getContext(), clickKey);
                                    openActivity(WebViewPager.class, new String[]{"startUrl"}, new String[]{url});
                                }
                            }

                        } else {
                            MobclickAgent.onEvent(App.getContext(), clickKey);
                            openActivity(WebViewPager.class, new String[]{"startUrl"}, new String[]{url});
                        }
                    }
                });
            }
        };
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            // 点击登录
            case R.id.login_layout:

                if (loginStatus()) {
                    MobclickAgent.onEvent(App.getContext(),
                            "v6_1_3_WD_grzl");
                    startActivity(new Intent(App.getContext(),
                            UserSettingActivity.class));

                }
                break;


            // 点击消息
            case R.id.msg_ly:
                if (loginStatus()) {

                    MobclickAgent.onEvent(App.getContext(), "v6_1_3_WD_xxzx");
                    openActivity(MsgActivity.class);
                }


                break;

            // 家庭管理
            case R.id.my_fam:
                if (loginStatus()) {
                    MobclickAgent.onEvent(App.getContext(), "v6_1_3_WD_jtcy");
                    openActivity(FamilyManagerActivity.class);
                }
                break;
            // 报告
            case R.id.report:

                if (loginStatus()) {
                    MobclickAgent.onEvent(App.getContext(), "v6_1_3_WD_fabg");
                    openActivity(ReportActivity.class);
                }

                break;
            // 收藏
            case R.id.my_collect:
                if (loginStatus()) {
                    MobclickAgent.onEvent(App.getContext(), "v6_1_3_WD_wdsc");
                    openActivity(MyFavorateActivity.class);
                }

                break;

            // 贝壳
            case R.id.shell_ly:

                if (loginStatus()) {
                    openActivity(ShellActivity.class);
                }


                break;
            // 保单验真
            case R.id.dingdan:

                MobclickAgent.onEvent(App.getContext(), "v6_1_3_WD_bdyz");
                String url3 = Constant.root_url + "html/common/checkguide";
                openActivity(WebViewPager.class, new String[]{"startUrl"}, new String[]{url3});


                break;
            // 我的问答
            case R.id.my_answer:

                if (loginStatus()) {
                    MobclickAgent.onEvent(App.getContext(), "v6_1_3_WD_wdwd");
                    openActivity(MyQuestionActivity.class);
                }

                break;
            // 我要理财
            case R.id.licai:
                if (loginStatus()) {
                    MobclickAgent.onEvent(App.getContext(), "v6_1_3_WD_wylc");
                    String uid = LoginInfo.getInstance(getActivity()).getUser().getU_id();
                    String url = Constant.root_url + "html/common/thirdpage?from=yc&uid=" + uid;
                    MobclickAgent.onEvent(App.getContext(), "v6_1_0_WD_wylc");
                    openActivity(WebViewPager.class, new String[]{"startUrl"}, new String[]{url});
                }

                break;
            // 邀请好友
            case R.id.invite:
                if (loginStatus()) {
                    MobclickAgent.onEvent(App.getContext(), "v6_1_3_WD_yqhy");
                    String url1 = Constant.root_url + "/html/invitejoin/invite" + "?uid=" + LoginInfo.getInstance(getActivity()).getUser().getU_id();
                    openActivity(WebViewPager.class, new String[]{"startUrl"}, new String[]{url1});
                }


                break;
            // 反馈
            case R.id.feedback:

                if (loginStatus()) {
                    MobclickAgent.onEvent(App.getContext(), "v6_1_3_WD_yjfk");
                    String uid = LoginInfo.getInstance(context).getUser()
                            .getU_id();
                    openActivity(WebViewPager.class, new String[]{"startUrl"},
                            new String[]{Constant.FEEDBACK_URL + "uid="
                                    + uid + "&data=" + Utils.deviceJson(context)
                                    + "&kind=0"});
                }
                break;
            // 系统设置
            case R.id.setting:
                MobclickAgent.onEvent(App.getContext(), "v6_1_3_WD_xtsz");
                openActivity(SettingActivity.class);
                break;


        }
    }


    public void loadLoginInfo() {
        if (LoginInfo.getInstance(App.getContext()).getUser()
                .getU_nick() != null) {
            this.login.setText("Hi," + LoginInfo
                    .getInstance(App.getContext()).getUser()
                    .getU_nick());
            dec.setText("我们在这里等你很久啦");

        } else {
            this.login.setText("点击登录");
            dec.setText("1秒登录,体验更多功能");
        }
        ImageUtil.setAvatarToRounderCorner(context, SpUtil.getInstance()
                .getString(SharedPreferanceKey.TEMPICURL), avatar, true);

    }


    public void updateShell() {
        if (LoginInfo.getInstance().isLogin()) {
            NetUtil netUtil = new NetUtil(getActivity(), JsonApi.USER_GETINTEGRAL);
            netUtil.postRequest("", new NetUtil.DataListener() {
                @Override
                public void onComplete(String data) {
                    String text = JSONUtil.getData("integral", data);
                    shell.setText(text+"贝壳");
                }
            });
        } else {
            shell.setText("");
        }
    }


    @Override
    public void onDestroy() {
        unRegistReceiver();
        super.onDestroy();
    }

    private void unRegistReceiver() {
        App.getContext().unregisterReceiver(receiveBroadCast);
    }

    private void initBroadCastReceiver() {
        // TODO Auto-generated method stub
        receiveBroadCast = new ReceiveBroadCast();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.ACTION_SUCCESS_UPLOAD_INFOR);
        filter.addAction(Constant.ACTION_SUCCESS_MODIFIED_INFOR);
        filter.addAction(Constant.ACTION_LOGOUT);

        filter.addAction(Constant.ACTION_SUCCESS_LOGIN);
        App.getContext().registerReceiver(receiveBroadCast,
                filter);
    }


    public boolean loginStatus() {

        boolean isLogin = (LoginInfo.getInstance(App.getContext())
                .getUser().getU_id() != null);

        if (!isLogin) {
            openActivity(LoginActivity.class, new String[]{"from"}, new String[]{"1"});
        }
        return isLogin;
    }

    class ReceiveBroadCast extends BroadcastReceiver {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            if (Constant.ACTION_SUCCESS_UPLOAD_INFOR.equals(arg1.getAction())) {
                loadLoginInfo();

            } else if (Constant.ACTION_SUCCESS_MODIFIED_INFOR.equals(arg1
                    .getAction())) {
                updateHeaderUI();
            } else if (Constant.ACTION_LOGOUT.equals(arg1.getAction())) {
                updateHeaderUI();
                loadLoginInfo();
            }
            if (Constant.ACTION_SUCCESS_LOGIN.equals(arg1.getAction())) {
                loadLoginInfo();

                if (getActivity() != null) {
                    ((MainActivity) getActivity()).initPush();
                }
            }


        }


        private void updateHeaderUI() {
            if (LoginInfo.getInstance(App.getContext()).getUser()
                    .getU_nick() != null) {
                login.setText("Hi," + LoginInfo.getInstance(App.getContext())
                        .getUser().getU_nick());
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            updateShell();
        }
    }
}
